package com.hawthorn.admin.service.syscompany.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hawthorn.admin.feign.redisService.RedisCompanyFeignService;
import com.hawthorn.admin.feign.redisService.RedisDeptFeignService;
import com.hawthorn.admin.model.po.SysCompanyPO;
import com.hawthorn.admin.model.po.SysDeptPO;
import com.hawthorn.admin.repository.SysCompanyMapper;
import com.hawthorn.admin.repository.SysDeptMapper;
import com.hawthorn.admin.repository.SysUserMapper;
import com.hawthorn.admin.service.syscompany.SysCompanyService;
import com.hawthorn.component.constant.DicConstant;
import com.hawthorn.component.utils.bean.Map2ObjUtil;
import com.hawthorn.entity.po.SysUserPO;
import com.hawthorn.platform.context.ContextHolder;
import com.hawthorn.platform.exception.BizCode;
import com.hawthorn.platform.redis.RedisMyClient;
import com.hawthorn.platform.service.ExcelApiService;
import com.hawthorn.platform.service.TransResultService;
import com.hawthorn.platform.utils.common.ArrayMyUtil;
import com.hawthorn.platform.utils.common.MyUtil;
import com.hawthorn.platform.utils.iassert.AssertMyUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * <p>todo 公司维护serviceImpl</p>
 * @author: andy.ten@tom.com | xukaixing@hotmail.com
 * @created: 2022/8/2 16:51
 * @version v1.0.1
 * @copyright: Copyright (c)  andyten
 */
@Service
public class sysCompanyServiceImpl implements SysCompanyService
{

  @Resource
  private TransResultService transResultService;

  @Resource
  private SysCompanyMapper sysCompanyMapper;

  @Resource
  private ExcelApiService excelApiService;

  @Resource
  private RedisCompanyFeignService redisCompanyFeignService;

  @Resource
  private SysDeptMapper sysDeptMapper;

  @Resource
  private RedisDeptFeignService redisDeptFeignService;

  @Resource
  private RedisMyClient redisMyClient;
  @Resource
  private SysUserMapper sysUserMapper;


  private HashMap<String, String> getTransHash()
  {
    HashMap<String, String> transHash = new HashMap<>();
    transHash.put("type", "dic|gslx");
    transHash.put("status", "dic|yxzt");
    transHash.put("kind", "dic|qdslb");

    return transHash;
  }

  /**
   * <p>todo 查询公司信息</p >
   * @param: page
   * @param: qc
   * @author: wcz
   * @date: 2022/6/21 20:24
   * @version: 1.0.1
   * Modification History:
   * Date Author Version Description
   * -----------------------------------------------------------
   * 2022/6/21 wcz v1.0.1
   */
  @Override
  public IPage<Map<String, Object>> findCompanies(Page<Map<String, Object>> page, String qc)
  {
    OrderItem oi = new OrderItem();
    oi.setColumn("code");
    oi.setAsc(true);
    List<OrderItem> al = page.getOrders();
    al.add(oi);
    page.setOrders(al);
    IPage<Map<String, Object>> companies = sysCompanyMapper.findCompanies(page, qc);
    return transResultService.transResult(companies, getTransHash());
  }

  /**
   * <p>todo 新增公司信息</p >
   * @param params  * @return : java.util.Map<java.lang.String,java.lang.Object>
   * @author: wcz
   * @date: 2022/6/24 10:12
   * @version: 1.0.1
   * Modification History:
   * Date Author Version Description
   * -----------------------------------------------------------
   * 2022/6/24 wcz v1.0.1 init
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public Map<String, Object> saveCompany(Map<String, Object> params)
  {
    List<SysCompanyPO> companyPOList = new ArrayList<>();
    SysCompanyPO sysCompanyPO = Map2ObjUtil.toObject(params, SysCompanyPO.class);
    AssertMyUtil.notNull(sysCompanyPO, BizCode.VARIABLE_NOT_NULL, "sysCompanyPO");
    //重名验证
    Integer companyIsExist = sysCompanyMapper.checkCompany(sysCompanyPO);
    if (companyIsExist != 0)
    {
      AssertMyUtil.errMsg("公司名称或简称重复");
    }

    // 设置oemCompanyId
    sysCompanyPO.setOemCompanyId(ContextHolder.getOemCompanyId());

    sysCompanyMapper.save(sysCompanyPO);

    // todo redis缓存
    companyPOList.add(sysCompanyPO);
    redisCompanyFeignService.cacheCompanyById(companyPOList);

    return transResultService.transResult(sysCompanyPO.toMaps(), getTransHash());
  }

  /**
   * <p>todo 修改公司信息</p >
   * @param id 用户id
   * @param params  * @return : java.util.Map<java.lang.String,java.lang.Object>
   * @author: wcz
   * @date: 2022/6/24 10:13
   * @version: 1.0.1
   * Modification History:
   * Date Author Version Description
   * -----------------------------------------------------------
   * 2022/6/24 wcz v1.0.1 init
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public Map<String, Object> updateCompany(Long id, Map<String, Object> params)
  {
    List<SysCompanyPO> companyPOList = new ArrayList<>();
    AssertMyUtil.notNull(id, BizCode.METHOD_ARGS_NOTNULL, "id");
    SysCompanyPO sysCompanyPo = sysCompanyMapper.selectById(id);
    Map2ObjUtil.toObject(params, sysCompanyPo);

    //重名验证
    // Integer companyIsExist = sysCompanyMapper.checkCompany(sysCompanyPo);
    // if (companyIsExist != 0)
    // {
    //   AssertMyUtil.errMsg("公司名称或简称重复");
    // }

    //查询下级组织有效状态
    if (sysCompanyMapper.findCid(id) != 0 && sysCompanyPo.getStatus() == 100202)
    {
      AssertMyUtil.errMsg("该公司下存在有效状态的组织，请到[组织管理]中将组织状态设置为[无效]，再进行修改！");
    }
    sysCompanyMapper.updateById(sysCompanyPo);
    // todo redis缓存
    companyPOList.add(sysCompanyPo);
    redisCompanyFeignService.cacheCompanyById(companyPOList);

    return transResultService.transResult(sysCompanyPo.toMaps(), getTransHash());
  }

  /**
   * <p>todo 导出</p >
   * @param response  前台数据
   * @param fileName 文件名
   * @param param  * @return : void
   * @author: wcz
   * @date: 2022/6/24 10:13
   * @version: 1.0.1
   * Modification History:
   * Date Author Version Description
   * -----------------------------------------------------------
   * 2022/6/24 wcz v1.0.1 init
   */
  @Override
  public void exportCompanyData(HttpServletResponse response, String fileName, Map<String, Object> param)
  {
    String header = MyUtil.getValue(param.get("header"));
    String params = MyUtil.getValue(param.get("params"));
    String qc = MyUtil.getConditionsWhere(params, null);
    List<List<String>> headList = new ArrayList<>();
    List<String> headFields = excelApiService.toHeader(header, headList);
    String fields = ArrayMyUtil.join(headFields.toArray(), ",");
    List<Map<String, Object>> dataList = sysCompanyMapper.exportCompanies(fields, qc);
    HashMap<String, String> transHash = new HashMap<>();
    transHash.put("type", "dic|gslx");
    transHash.put("status", "dic|yxzt");
    transHash.put("kind", "dic|qdslb");
    excelApiService.export(response, fileName, headFields, headList, dataList, transHash);
  }

  /**
   * <p>todo 修改状态</p >
   * @param id 用户id
   * @param params  * @return : java.util.Map<java.lang.String,java.lang.Integer>
   * @author: wcz
   * @date: 2022/6/24 10:14
   * @version: 1.0.1
   * Modification History:
   * Date Author Version Description
   * -----------------------------------------------------------
   * 2022/6/24 wcz v1.0.1 init
   */
  @Override
  public Map<String, Object> changeStatus(Long id, String params)
  {
    AssertMyUtil.notNull(id, BizCode.METHOD_ARGS_NOTNULL, "id");
    //查询下级组织有效状态
    if (sysCompanyMapper.findCid(id) != 0 && Integer.parseInt(params) == 100202)
    {
      AssertMyUtil.errMsg("修改失败,该组织下存在启用组织!");
    }
    SysCompanyPO sysCompanyPO = sysCompanyMapper.selectById(id);

    UpdateWrapper<SysCompanyPO> updateWrapper = new UpdateWrapper<>();
    sysCompanyPO.setStatus(Integer.parseInt(params));
    updateWrapper.eq("id", id);
    sysCompanyMapper.update(sysCompanyPO, updateWrapper);

    // todo redis缓存
    List<SysCompanyPO> companyPOList = new ArrayList<>();
    companyPOList.add(sysCompanyPO);
    redisCompanyFeignService.cacheCompanyById(companyPOList);

    return sysCompanyPO.toMaps();
  }


  @Override
  public Map<String, Object> saveComDept(Map<String, Object> params)
  {
    AssertMyUtil.notNull(params, BizCode.METHOD_ARGS_NOTNULL, "params");
    Map<String, Object> resultMap = new HashMap<>();
    SysCompanyPO companyPO = sysCompanyMapper.selectById(!StringUtils.isEmpty(params.get("companyId")) ? params.get(
        "companyId").toString() : "");
    if (Objects.isNull(companyPO))
    {
      companyPO = new SysCompanyPO();
      companyPO.setType(Long.valueOf(DicConstant.GSLX_02));
      companyPO.setCode(!StringUtils.isEmpty(params.get("ccode")) ? params.get("ccode").toString() :
          "T" + getNum());
      companyPO.setCname(params.get("ccname").toString());
      companyPO.setSname(StringUtils.isEmpty(params.get("csname")) ? "" : params.get("csname").toString());
      companyPO.setStatus(Integer.valueOf(DicConstant.YXBS_01));
      //为pc调用
      if (!StringUtils.isEmpty(params.get("oemCompanyId")))
      {
        companyPO.setOemCompanyId(!StringUtils.isEmpty(params.get("oemCompanyId")) ? Long.parseLong(params.get("oemCompanyId").toString()) : null);
        //不为空 麒麟云店调用
      } else if (!StringUtils.isEmpty(params.get("customerDeptId")))
      {
        SysDeptPO sysDeptPO = sysDeptMapper.selectById(params.get("customerDeptId").toString());
        companyPO.setOemCompanyId(sysDeptPO != null ? sysDeptPO.getOemCompanyId() : null);
        //不为空为麒麟通调用
      } else if (!StringUtils.isEmpty(params.get("userId")))
      {
        SysUserPO sysUserPO = sysUserMapper.selectById(params.get("userId").toString());
        companyPO.setOemCompanyId(sysUserPO != null ? sysUserPO.getOemCompanyId() : null);
      }
      sysCompanyMapper.save(companyPO);
    } else
    {
      companyPO.setType(Long.valueOf(DicConstant.GSLX_02));
      companyPO.setCname(params.get("ccname").toString());
      companyPO.setSname(params.get("csname").toString());
      companyPO.setStatus(Integer.valueOf(DicConstant.YXBS_01));
      //为pc调用
      if (!StringUtils.isEmpty(params.get("oemCompanyId")))
      {
        companyPO.setOemCompanyId(!StringUtils.isEmpty(params.get("oemCompanyId")) ? Long.parseLong(params.get("oemCompanyId").toString()) : null);
        //不为空 麒麟云店调用
      } else if (!StringUtils.isEmpty(params.get("customerDeptId")))
      {
        SysDeptPO sysDeptPO = sysDeptMapper.selectById(params.get("customerDeptId").toString());
        companyPO.setOemCompanyId(sysDeptPO != null ? sysDeptPO.getOemCompanyId() : null);
        //不为空为麒麟通调用
      } else if (!StringUtils.isEmpty(params.get("userId")))
      {
        SysUserPO sysUserPO = sysUserMapper.selectById(params.get("userId").toString());
        companyPO.setOemCompanyId(sysUserPO != null ? sysUserPO.getOemCompanyId() : null);
      }


      sysCompanyMapper.updateById(companyPO);
    }
    resultMap.put("companyId", companyPO.getId());
    List<SysCompanyPO> companyPOList = new ArrayList<>();
    companyPOList.add(companyPO);
    redisCompanyFeignService.cacheCompanyById(companyPOList);
    SysDeptPO sysDeptPO =
        sysDeptMapper.selectById(!StringUtils.isEmpty(params.get("deptId")) ? params.get("deptId").toString() : "");
    if (Objects.isNull(sysDeptPO))
    {
      sysDeptPO = new SysDeptPO();
      sysDeptPO.setLevel(Long.valueOf(DicConstant.JGJB_06));
      sysDeptPO.setDeptType(Long.valueOf(params.get("ddeptype").toString()));
      sysDeptPO.setCompanyId(companyPO.getId());
      sysDeptPO.setPid(Long.valueOf(params.get("dpid").toString()));
      sysDeptPO.setDcode(!StringUtils.isEmpty(params.get("ddcode")) ? params.get("ddcode").toString() :
          "T" + getNum());
      sysDeptPO.setDname(params.get("ddname").toString());
      sysDeptPO.setSname(StringUtils.isEmpty(params.get("dsname")) ? "" : params.get("dsname").toString());
      sysDeptPO.setBizStatus(Long.valueOf(DicConstant.ZZYWZT_01));
      sysDeptPO.setStatus(Integer.valueOf(DicConstant.YXBS_01));
      //为pc调用
      if (!StringUtils.isEmpty(params.get("oemCompanyId")))
      {
        sysDeptPO.setOemCompanyId(!StringUtils.isEmpty(params.get("oemCompanyId")) ? Long.parseLong(params.get("oemCompanyId").toString()) : null);
        //不为空 麒麟云店调用
      } else if (!StringUtils.isEmpty(params.get("customerDeptId")))
      {
        SysDeptPO sysDeptPO1 = sysDeptMapper.selectById(params.get("customerDeptId").toString());
        sysDeptPO.setOemCompanyId(sysDeptPO1 != null ? sysDeptPO1.getOemCompanyId() : null);
        //不为空为麒麟通调用
      } else if (!StringUtils.isEmpty(params.get("userId")))
      {
        SysUserPO sysUserPO = sysUserMapper.selectById(params.get("userId").toString());
        sysDeptPO.setOemCompanyId(sysUserPO != null ? sysUserPO.getOemCompanyId() : null);
      }

      sysDeptMapper.save(sysDeptPO);
    } else
    {
      sysDeptPO.setLevel(Long.valueOf(DicConstant.JGJB_06));
      sysDeptPO.setDeptType(Long.valueOf(params.get("ddeptype").toString()));
      sysDeptPO.setCompanyId(companyPO.getId());
      sysDeptPO.setPid(Long.valueOf(params.get("dpid").toString()));
      sysDeptPO.setDname(params.get("ddname").toString());
      sysDeptPO.setSname(params.get("dsname").toString());
      sysDeptPO.setBizStatus(Long.valueOf(DicConstant.ZZYWZT_01));
      sysDeptPO.setStatus(Integer.valueOf(DicConstant.YXBS_01));

      //为pc调用
      if (!StringUtils.isEmpty(params.get("oemCompanyId")))
      {
        sysDeptPO.setOemCompanyId(!StringUtils.isEmpty(params.get("oemCompanyId")) ? Long.parseLong(params.get("oemCompanyId").toString()) : null);
        //不为空 麒麟云店调用
      } else if (!StringUtils.isEmpty(params.get("customerDeptId")))
      {
        SysDeptPO sysDeptPO1 = sysDeptMapper.selectById(params.get("customerDeptId").toString());
        sysDeptPO.setOemCompanyId(sysDeptPO1 != null ? sysDeptPO1.getOemCompanyId() : null);
        //不为空为麒麟通调用
      } else if (!StringUtils.isEmpty(params.get("userId")))
      {
        SysUserPO sysUserPO = sysUserMapper.selectById(params.get("userId").toString());
        sysDeptPO.setOemCompanyId(sysUserPO != null ? sysUserPO.getOemCompanyId() : null);
      }
      sysDeptMapper.updateById(sysDeptPO);
    }
    resultMap.put("deptId", sysDeptPO.getId());
    redisDeptFeignService.updateDept(sysDeptPO);
    return resultMap;
  }

  public String getNum()
  {
    //计数器为了记录数组下标
    int index = 0;
    //new一个数组对象和Random对象
    int[] arr = new int[5];
    for (int i = 0; i < arr.length; i++)
    {
      arr[i] = -1;
    }
    StringBuffer buffer = new StringBuffer();
    Random random = new Random();
    while (index < arr.length)
    {
      //变量count也是为了计数
      int count = 0;
      int num = random.nextInt(6);
      for (int i = 0; i < arr.length; i++)
      {
        if (arr[i] != num) count++;
      }
      if (count == arr.length)
      {
        buffer.append(num);
        index++;
      }
    }
    return buffer.toString();
  }


}
